package logic

import (
	"math/rand"
	"strconv"
	"strings"
	"time"

	"gitee.com/leicc/go-orm"
	"gitee.com/leicc/go-core"
	"gitee.com/leicc/go-orm/log"
	"gitee.com/leicc/go-app-core/logics"
)

const (
	IMSRVNAME = "go.http.srv.im"
	DBNAMEIM  = "webim"
	VERSION   = "v1.0.0"
)

type Config struct {
	core.Config
	Appid 	int64 		`yaml:"appid"`
	ImSrv 	string      `yaml:"imsrv"`
	MQueue 	string 		`yaml:"mqueue"`
	MQNameSrv []string 	`yaml:"mqnamesrv"`
}

var GConfig *Config = nil

func NewConfig(conf string) *Config {
	GConfig = &Config{}
	GConfig.ConfAddr = conf
	GConfig.App.Name = IMSRVNAME
	GConfig.App.Version = VERSION
	//自动去加载配置 完成对象结构初始化
	GConfig.Load(GConfig)
	NewState() //redis数据的统计
	GConfig.messageQueue()
	GConfig.loadMysql()
	return GConfig
}

//加载数据库信息
func (c *Config) loadMysql()  {
	c.LoadDBRemote(DBNAMEIM, c.DiSrv)
}

//kafka topic 命名要求
func (c *Config) messageQueue() {
	inerIp, err := orm.GetLocalRandomIPv4()
	if err != nil {//获取内网ip地址
		inerIp = "127.0.0.1"
	}
	inerIp = strings.ReplaceAll(inerIp,".", "")
	npos := strings.IndexByte(c.App.Host, ':')
	if npos > -1 {
		inerIp += c.App.Host[npos+1:]
	} else {//随机其一个消息队列名称
		inerIp += strconv.FormatInt(rand.Int63(), 10)
	}
	c.MQueue = "TP"+inerIp
	log.Write(log.INFO, "Kafka Mqueue Topic{", c.MQueue, "}")
}

//获取记录的uuid
func GetUuidString() string {
	tmstr := strconv.FormatInt(time.Now().UnixNano(), 10)
	nsize := 28 - len(tmstr)
	if nsize > 0 {//填充满28个字符
		tmstr += orm.RandString(nsize)
	}
	buffer := make([]byte, 0)
	for idx := 0; idx < 28; idx++ {
		if idx == 8 || idx == 12 || idx == 16 || idx == 20 {
			buffer = append(buffer, '-')
		}
		buffer = append(buffer, tmstr[idx])
	}
	return string(buffer)
}

//是否句柄资源数据信息
func DeferRelease() {
	orm.GdbPoolSt.Release()
	if GMQueue != nil {
		GMQueue.Release()
	}
	if logics.CRedis != nil {
		logics.CRedis.Close()
	}
	if GStore != nil {
		GStore.Close()
	}
}